import requests

from utils.file_tools import FileTools
from utils.log_util import logger


class FeiShu:
    def __init__(self):
        # 切换环境
        env_config = FileTools.read_yaml("env")
        default_env = env_config["default"]
        self.base_url = env_config[default_env]

    def __set_token(self, requests_info):
        # 避免重复获取token
        if not hasattr(self, "token"):
            # 定义请求参数
            url = f"{self.base_url}/auth/v3/tenant_access_token/internal"
            body_data = {
                "app_id": "cli_a385e987c478100d",
                "app_secret": "Y1eupiyGDlyF95ufMQ1MugREpPXKLBOD"
            }
            # 发送请求
            req = requests.post(url, json=body_data)
            token = req.json()["tenant_access_token"]
            logger.debug(f"日志打印：{token}")

        # 如果有headers就追加，如果没有headers则添加
        if requests_info.get("headers"):
            requests_info["headers"].update({"Authorization": f"Bearer {token}"})
        else:
            requests_info["headers"] = {"Authorization": f"Bearer {token}"}
        return requests_info

    def send(self, method, url, **kwargs):
        """
        针对requests做二次封装。日志信息、响应格式规范
        :return:
        """
        # 在发起请求之前，将token信息放到headers中
        kwargs = self.__set_token(kwargs)
        # 发起请求
        req = requests.request(method, self.base_url + url, **kwargs)
        # 打印日志
        logger.debug(f"日志打印：{req.json()}")
        return req

